import React from 'react'
import Reflux from 'reflux'
import { Col, Row } from 'antd'
import { LdhDetailPage, LdhFieldSet } from '@biz/PageCompnents'
import { Message, LdhTable } from '@biz/Components'
import GUtils from '@/utils'

import { createAction } from '../Action'
import Config from '../config'
import Store from '../Store'
import '../style.less'
import '../../biz/style.less'
import { LdhButton } from '../../../../biz/Components'
import RefundModal from './RefundModal'
import { Button, Tag } from 'antd'
import { onPostEndWashOrderXhr } from '@/api/coupon'
import { couponChannelMap } from '../config'
const prefix = 'order-detail wash-order-detail'
export default class WashOrderDetail extends Reflux.Component {
  constructor(props) {
    super(props)
    this.action = createAction()
    this.config = Config(this.action)
    this.store = new Store(props, this.config, this.action)
    this.className = prefix
  }

  componentDidMount() {
    let id = GUtils.getQueryString('id')
    if (!id) {
      Message.error('参数非法！')
      this.setState({ detailStatus: 'view' })
      return
    }
    this.action.getDetail(id, (detail) => {
      let {
        billMinutes = 0,
        completedTime,
        productStartPrice,
        productStartMinute,
        productMinutePrice,
        timeAmount,
        useDurationStr = '',
        giftBalanceDiscountAmount,
        couponDiscountAmount,
        couponFreeTime,
      } = detail
      // 还没支付
      let feeList = [
        { name: '起付金额', price: productStartPrice, time: '', amount: '' },
        { name: '计时金额', price: productMinutePrice, time: '', amount: '' },
        {
          name: '优惠券抵扣',
          price: '',
          time: couponFreeTime,
          amount: -(couponDiscountAmount ?? 0),
        },
        {
          name: '赠送余额抵扣',
          price: giftBalanceDiscountAmount,
          time: '',
          amount: -(giftBalanceDiscountAmount ?? 0),
        },
      ]
      if (!completedTime) {
      } else if (billMinutes <= productStartMinute) {
        feeList[0].time = useDurationStr
        feeList[0].amount = productStartPrice
      } else {
        feeList[0].time = productStartMinute
        feeList[0].amount = productStartPrice

        feeList[1].time = billMinutes - productStartMinute
        feeList[1].amount = timeAmount
      }

      if (detail.vipDiscountAmount) {
        feeList.push({
          name: '会员抵扣',
          price: '',
          time: -detail.vipFreeTime,
          amount: -detail.vipDiscountAmount,
          className: 'vip-amount',
        })
      }

      detail.feeList = feeList

      // 退款
      if (detail.status == 4) {
        let { refundAmount, refundTime, refundReason } = detail
        detail.refundList = [
          { amount: refundAmount, time: refundTime, reason: refundReason },
        ]
      }

      // 订单结算
      let settlementList = []
      if (detail.settlement && detail.settlement.detailList) {
        // 映射结算明细数据
        settlementList = detail.settlement.detailList.map((item) => ({
          name: item.typeLabel || '',
          amount: item.sourceAmount,
          ratio: item.ratio,
          subtotal: item.amount,
        }))
        // 添加合计行
        if (
          detail.settlement.totalAmount !== undefined &&
          detail.settlement.totalAmount !== null
        ) {
          settlementList.push({
            name: '合计',
            amount: null,
            ratio: null,
            subtotal: detail.settlement.totalAmount,
            isTotal: true,
          })
        }
      }
      detail.settlementList = settlementList
    })
  }

  renderRow(f1, v1, f2, v2) {
    return (
      <Row gutter={20} className="value-row">
        <Col flex="200px">{f1} </Col>
        <Col span={6}>{v1} </Col>
        <Col flex="120px">{f2}</Col>
        <Col span={6}>{v2} </Col>
      </Row>
    )
  }
  // 结束洗车订单
  async endWashOrder() {
    let id = GUtils.getQueryString('id')
    try {
      const res = await onPostEndWashOrderXhr({ id })
      if (res?.success) {
        Message.success('结束订单成功')
        this.componentDidMount() // 刷新页面数据
      } else {
        Message.error(res?.message || '结束订单失败')
      }
    } catch (e) {
      Message.error('结束订单失败：' + e)
    }
  }
  render() {
    let { loading, detail = {} } = this.state
    let o = detail
    let canRefund = 2 == o.status
    let billMinutes = o.billMinutes == undefined ? '' : o.billMinutes

    console.log('detail', detail)
    return (
      <LdhDetailPage className={this.className}>
        {detail?.status === 1 && (
          <div className="finish-order-btn">
            <Button type="primary" onClick={this.endWashOrder.bind(this)}>
              结束订单
            </Button>
          </div>
        )}
        <LdhFieldSet
          title="洗车订单"
          loading={loading}
          custom={
            canRefund && (
              <LdhButton type="primary" onClick={this.action.preRefund}>
                退款
              </LdhButton>
            )
          }
        >
          {this.renderRow(
            '订单号',
            <div className="order-no-wrap">
              <a>{o.orderNo}</a>
              <div style={{ marginLeft: '4px' }}>
                {o?.couponChannel !== undefined &&
                  o?.couponChannel !== null &&
                  couponChannelMap?.[o?.couponChannel] && (
                    <Tag color="processing">
                      {couponChannelMap?.[o?.couponChannel]}
                    </Tag>
                  )}
              </div>
            </div>,
            '订单状态',
            GUtils.renderWashOrderStatus(o)
          )}
          {this.renderRow(
            '订单门店',
            o.shopName,
            '下单时间',
            GUtils.dateTimeFormatter(o.createTime)
          )}
          {this.renderRow(
            '用户昵称',
            o.userNickname,
            '开始时间',
            GUtils.dateTimeFormatter(o.startTime)
          )}
          {this.renderRow(
            '用户手机号',
            o.userPhone,
            '结束时间',
            GUtils.dateTimeFormatter(o.completedTime)
          )}
          {this.renderRow(
            '用户UID',
            (o.userId + '').padStart(6, '0'),
            '用时',
            o.useDurationStr || ''
          )}
        </LdhFieldSet>

        <LdhFieldSet title="订单费用明细" loading={loading}>
          <LdhTable
            loading={loading}
            columns={feeColumns}
            rowKey="name"
            dataSource={o.feeList}
            pagination={false}
            scroll={false}
          />

          <div className="flex-between">
            <div className="pay-value">
              订单应付 <span>￥ {o.totalAmount}</span>
            </div>
            <div className="pay-value">
              余额实付 <span>￥ {o.realBalanceAmount}</span>
            </div>
          </div>
        </LdhFieldSet>

        <LdhFieldSet title="退款记录" loading={loading}>
          <LdhTable
            loading={loading}
            columns={refundColumns}
            rowKey="name"
            dataSource={o.refundList}
            pagination={false}
            scroll={false}
          />
        </LdhFieldSet>

        <LdhFieldSet title="订单结算" loading={loading}>
          <LdhTable
            loading={loading}
            columns={settlementColumns}
            rowKey="name"
            dataSource={o.settlementList}
            pagination={false}
            scroll={false}
          />
        </LdhFieldSet>

        <LdhFieldSet title="交易记录" loading={loading}>
          <LdhTable
            loading={loading}
            columns={transactionColumns}
            rowKey="name"
            dataSource={o.transactionList}
            pagination={false}
            scroll={false}
          />
        </LdhFieldSet>

        <RefundModal
          action={this.action}
          store={this.state}
          onSubmitCallback={this.componentDidMount.bind(this)}
        />
      </LdhDetailPage>
    )
  }
}

const feeColumns = [
  { title: '费用类型', dataIndex: 'name', width: 200 },
  { title: '金额', dataIndex: 'price', width: 200 },
  { title: '分钟', dataIndex: 'time', width: 200 },
  {
    title: '合计',
    dataIndex: 'amount',
    width: 200,
    render: (v, vo) => <div className={vo.className}>{v}</div>,
  },
]

const refundColumns = [
  {
    title: '时间',
    dataIndex: 'time',
    width: 200,
    render: (v) => GUtils.dateTimeFormatter(v),
  },
  { title: '原因', dataIndex: 'reason', width: 200 },
  { title: '金额', dataIndex: 'amount', width: 200 },
]

const settlementColumns = [
  { title: '收入类型', dataIndex: 'name', width: 200 },
  {
    title: '金额',
    dataIndex: 'amount',
    width: 200,
    render: (v) => {
      if (v === null || v === undefined) return '/'
      const num = Number(v)
      return isNaN(num) ? '/' : num.toFixed(2)
    },
  },
  {
    title: '结算比例',
    dataIndex: 'ratio',
    width: 200,
    render: (v) => {
      if (v === null || v === undefined) return '/'
      const num = Number(v)
      return isNaN(num) ? '/' : num.toFixed(2)
    },
  },
  {
    title: '小计',
    dataIndex: 'subtotal',
    width: 200,
    render: (v, vo) => {
      const num = Number(v)
      const displayValue = isNaN(num) ? '0.00' : num.toFixed(2)
      if (vo.isTotal) {
        return <strong>{displayValue}</strong>
      }
      return displayValue
    },
  },
]

const transactionColumns = [
  { title: '商户号', dataIndex: 'name', width: 200 },
  { title: '交易号', dataIndex: 'name', width: 200 },
  {
    title: '支付时间',
    dataIndex: 'time',
    width: 200,
    render: (v) => GUtils.dateTimeFormatter(v),
  },
  { title: '支付金额', dataIndex: 'amount', width: 200 },
]
